package com.turkcell.dv.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.turkcell.dv.model.UserDOM;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional(readOnly = true)
public class UserDAOImpl implements UserDAO {

	private static final Logger logger = LoggerFactory.getLogger(UserDAOImpl.class);

	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sf) {
		this.sessionFactory = sf;
	}
	@Override
	public UserDOM addUser(UserDOM u) {
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(u);
		logger.info("User saved successfully, User Details= " + u);
		return u;
	}

	@Override
	public UserDOM updateUser(UserDOM u) {
		Session session = this.sessionFactory.getCurrentSession();
		session.update(u);
		logger.info("User updated successfully, User Details=" + u);
		return u;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserDOM> listUsers() {
		Session session = this.sessionFactory.getCurrentSession();
		List<UserDOM> usersList = session.createQuery("from UserDOM").list();
		for (UserDOM u : usersList) {
			logger.info("User List::" + u);
		}
		return usersList;
	}

	@Override
	public UserDOM getUserById(long id) {
		Session session = this.sessionFactory.getCurrentSession();
		UserDOM u = (UserDOM) session.load(UserDOM.class, new Long(id));
		logger.info("User loaded successfully, User details=" + u);
		return u;
	}

	@Override
	public void removeUser(long id) {
		Session session = this.sessionFactory.getCurrentSession();
		UserDOM u = (UserDOM) session.load(UserDOM.class, new Long(id));
		if (null != u) {
			session.delete(u);
		}
		logger.info("User deleted successfully, User details=" + u);
	}
	@SuppressWarnings("unchecked")
	@Override
	public UserDOM getUserByUsername(String username) {
		Session session = this.sessionFactory.getCurrentSession();
		Query query = session.createQuery("from UserDOM U WHERE U.username = :username");
		query.setParameter("username", username);
		List<UserDOM> resultSet = query.list();
		for (UserDOM u : resultSet) {
			logger.info("User List::" + u);
		}
		if(resultSet.size() == 1) {
			return resultSet.get(0);
		} else {
			return null;
		}
	}
}
